package com.leyou.order.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.wxpay.sdk.WXPay;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.order.config.PayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付工具类
 */
@Component
@Slf4j
public class PayHelper {

    @Autowired
    private PayProperties payProps;
    @Autowired
    private WXPay wxPay;

    /**
     * 获取支付二维码链接（下单方法）
     */
    public String unifiedOrder(Long orderId,Long totalFee){
        // 请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优商城-订单支付");//描述
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", payProps.getNotifyUrl());
        data.put("trade_type", payProps.getPayType());  // 此处指定为扫码支付

        try {
            Map<String, String> resp = wxPay.unifiedOrder(data);

            //校验结果是否成功： return_code 和result_code都为SUCCESS的时候有返回
            String returnCode = resp.get("return_code");
            String resultCode = resp.get("result_code");

            if(StringUtils.isNotEmpty(returnCode) &&
                    StringUtils.isNotEmpty(resultCode)
                    && returnCode.equals("SUCCESS")
                    && resultCode.equals("SUCCESS")){
                log.info("【微信支付】获取支付链接成功");
                //成功
                return resp.get("code_url");
            }else{
                log.error("【微信支付】获取支付链接失败:"+resp.get("err_code_des"));
                //失败
                throw new LyException(500,"【微信支付】获取支付链接失败:"+resp.get("err_code_des"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            //失败
            log.error("【微信支付】获取支付链接失败,"+e.getMessage());
            throw new LyException(500,"【微信支付】获取支付链接失败,"+e.getMessage());
        }
    }
    public void checkResp(Map<String, String> resp) {
        if(!org.apache.commons.lang3.StringUtils.equals(resp.get("return_code"), "SUCCESS")){
            log.error("【获取微信支付url工具类】网络通信异常！异常信息为：{}", resp.get("return_msg"));
            throw new LyException(501, "【获取微信支付url工具类】网络通信异常！");
        }
        if(!org.apache.commons.lang3.StringUtils.equals(resp.get("result_code"), "SUCCESS")){
            log.error("【获取微信支付url工具类】业务异常！异常信息为：{}", resp.get("err_code_des"));
            throw new LyException(501, "【获取微信支付url工具类】业务异常！");
        }
    }
}
